/*
 * UGView.cpp
 *
 *  Created on: Dec 17, 2012
 *      Author: tony
 */

#include "UGView.h"

namespace ugame {
    UGView::UGView(){
        this->eventNotifier = UGApplication::getInstance()->getSharedEventNotifier();
        CC_SAFE_RETAIN(this->eventNotifier);
    }
    
    UGView::~UGView(){
        CC_SAFE_RELEASE(this->eventNotifier);
    }
    
    void UGView::notify(UGEvent* event) {
        this->getEventNotifier()->notifyEvent(event);
    }
    
    void UGView::notify(int eventId, int eventType, Ref* sender, float delayTime, void* eventArg) {
        UGEvent* event = UGDefaultEvent::create(eventId, eventType, sender, delayTime, eventArg);
        this->getEventNotifier()->notifyEvent(event);
    }
    
    RenderTexture* UGView::createStroke(Sprite* label, int size, Color3B color, GLubyte opacity) {
        RenderTexture* rt = CCRenderTexture::create(label->getTexture()->getContentSize().width + size * 2,
                                                      label->getTexture()->getContentSize().height+size * 2);
        Point originalPos = label->getPosition();
        Color3B originalColor = label->getColor();
        GLubyte originalOpacity = label->getOpacity();
        bool originalVisibility = label->isVisible();
        
        label->setColor(color);
        label->setOpacity(opacity);
        label->setVisible(true);
        BlendFunc originalBlend = label->getBlendFunc();
        BlendFunc bf = {GL_SRC_ALPHA, GL_ONE};
        label->setBlendFunc(bf);
        
        Point bottomLeft = Point(label->getTexture()->getContentSize().width * label->getAnchorPoint().x + size,
                                 label->getTexture()->getContentSize().height * label->getAnchorPoint().y + size);
        Point positionOffset= Point(- label->getTexture()->getContentSize().width / 2,
                                    - label->getTexture()->getContentSize().height / 2);
        Point position = originalPos - positionOffset;
        
        rt->begin();
        for (int i = 0; i < 360; i+= 15) { // you should optimize that for your needs
            label->setPosition(Point(bottomLeft.x + sin(CC_DEGREES_TO_RADIANS(i)) * size,
                                   bottomLeft.y + cos(CC_DEGREES_TO_RADIANS(i)) * size));
            label->visit();
        }
        rt->end();
        
        label->setPosition(originalPos);
        label->setColor(originalColor);
        label->setBlendFunc(originalBlend);
        label->setVisible(originalVisibility);
        label->setOpacity(originalOpacity);
        
        rt->setPosition(position);
        return rt;
    }
}